package com.tianji.job;

import com.tianji.medical.pojo.PatientMedication;
import com.tianji.medical.service.PatientMedicationService;
import com.tianji.mq.produce.MedicationRemindProducer;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
public class PatientMedicationJob {

    private final PatientMedicationService patientMedicationService;

    private final MedicationRemindProducer medicationRemindProducer;


    //定时开始发放优惠券
    @XxlJob("PatientMedicationTask")
    public void PatientMedicationTask() {
        try {
            XxlJobHelper.log("****  定时检查患者用药信息 ****");
            //获取当前分片总数和当前分片索引
            int shardIndex = XxlJobHelper.getShardIndex();
            int shardTotal = XxlJobHelper.getShardTotal();

            //处理需要发送服药的信息
            List<PatientMedication> medications = patientMedicationService
                    .findByShard(shardIndex, shardTotal, LocalDateTime.now());
            for (PatientMedication medication : medications) {
                medicationRemindProducer.sendReminder(medication);
            }
        } catch (Exception e) {
            XxlJobHelper.log("更新优惠券状态时出错: "+e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
